package cn.orangelite.ai.service.impl;

import cn.hutool.json.JSONUtil;
import cn.orangelite.ai.domain.AiGptMessageLog;
import cn.orangelite.ai.domain.dto.Message;
import cn.orangelite.ai.mapper.AiGptMessageLogMapper;
import cn.orangelite.ai.service.IAiGptMessageLogService;
import cn.orangelite.common.core.utils.DateUtils;
import cn.orangelite.common.security.utils.SecurityUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AiGptMessageLogServiceImpl extends ServiceImpl<AiGptMessageLogMapper, AiGptMessageLog> implements IAiGptMessageLogService {

    @Override
    public AiGptMessageLog saveMessageLog(Integer logId, Message message) {
        AiGptMessageLog aiGptMessageLog;
        if(logId==null){
            aiGptMessageLog = new AiGptMessageLog();
            aiGptMessageLog.setUserId(SecurityUtils.getUserId());
            aiGptMessageLog.setUseNumber(0);

            List<Message> list = new ArrayList<>();
            list.add(message);
            aiGptMessageLog.setUseValue(JSONUtil.toJsonStr(list));

            aiGptMessageLog.setGptKey("");
            aiGptMessageLog.setCreateTime(DateUtils.getNowDate());
            aiGptMessageLog.setUpdateTime(DateUtils.getNowDate());

            this.save(aiGptMessageLog);
        }else{
            aiGptMessageLog = baseMapper.selectById(logId);
            String useValue = aiGptMessageLog.getUseValue();
            List<Message> list = JSONUtil.toList(useValue, Message.class);
            list.add(message);
            aiGptMessageLog.setUseValue(JSONUtil.toJsonStr(list));
            aiGptMessageLog.setUpdateTime(DateUtils.getNowDate());

            this.updateById(aiGptMessageLog);

        }
        return aiGptMessageLog;
    }
}
